import path from 'node:path'
import { globSync } from 'glob'
// import vue from 'rollup-plugin-vue';
import esbuild from 'rollup-plugin-esbuild';
import postcss from 'rollup-plugin-postcss';
// import replace from '@rollup/plugin-replace';
import commonjs from '@rollup/plugin-commonjs';
import nodeResolve from '@rollup/plugin-node-resolve';
import multiInput from 'rollup-plugin-multi-input';
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'

const esConfig = {
  input: [
    // 'packages/pc/**/index.jsx',
    path.resolve(__dirname, '..', 'packages/pc/button/index.jsx'),
    path.resolve(__dirname, '..', 'packages/pc/link/index.jsx'),
  ],
  external: ['vue'],
  output: {
    dir: 'dist/',
    format: 'esm',
    sourcemap: false,
    // banner: `import './style.css';`,
    // doc:https://www.rollupjs.com/configuration-options/#output-entryfilenames
    entryFileNames: (chunkInfo) => `${chunkInfo.name.replace(/packages\//, '')}.js`,
    chunkFileNames: 'pc/_chunks.js',
    globals: {
      vue: 'Vue',
    },
  },
  plugins: [
    multiInput.default(),
    nodeResolve(),
    vue(),
    vueJsx(),
    commonjs(),
    esbuild.default({
      target: 'esnext',
      minify: false,
      jsx: 'preserve',
      target: 'es2016',
      tsconfig: 'tsconfig.build.json',
      loaders: {
        '.vue': 'ts',
      },
    }),
  ],
}

const getCSSConfig = (entry) => {
  const input = path.resolve(__dirname, '..', entry)
  const extract = entry.replace(/packages\\/, '').replace(/\.less/, '.css')
  return {
    input,
    output: {
      dir: 'dist/',
      format: 'esm',
      sourcemap: false,
    },
    plugins: [
      postcss({
        extract,
        minimize: true,
        sourceMap: false,
        extensions: ['.scss', '.css', '.less'],
      }),
      // https://stackoverflow.com/questions/75944042/how-can-i-prevent-rollup-js-from-creating-an-empty-chunk-when-building-scss
      {
        generateBundle: (option, bundle) => {
          Object.keys(bundle).forEach(key => {
            if (bundle[key].type !== 'asset') {
              delete bundle[key];
            }
          });
        },
      },
    ],
  }
}

const lessList = globSync('packages/pc/**/*.less')

const cssConfig = lessList.map(item => getCSSConfig(item))
export default [
  esConfig,
  ...cssConfig,
];
